package com.flute.haflute.agent.manage;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Set;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.agent.topo.ClusterTopoDBService;
import com.flute.haflute.agent.topo.Node;
import com.flute.haflute.common.ClusterContext;
import com.flute.haflute.jobbox.base.RunProcessInterface;
import com.flute.haflute.net.messaging.Message;
import com.flute.haflute.net.messaging.MessageFactory;
import com.flute.haflute.net.messaging.MessagingService;

/**
 * 节点中进行集群管理的基本服务，主要负责：<br>
 * 
 * 1. 关闭集群级别的所有节点的后台服务和关闭时需要清理的资源
 * 
 * 2. 系统退出时清理相关资源
 */
public class GeneralClusterManager implements RunProcessInterface {

	private static Logger logger = LoggerFactory
			.getLogger(GeneralClusterManager.class);

	@Override
	public void callMain(String... params) {

	}

	/*
	 * @see com.flute.haflute.jobbox.base.RunProcessInterface#isInitialized()
	 */
	@Override
	public boolean isInitialized() {
		return true;
	}

	/*
	 * @see com.flute.haflute.jobbox.base.RunProcessInterface#shutdown()
	 */
	@Override
	public void shutdown() {
		Set<Node> allNodes = ClusterTopoDBService.getInstance()
				.getNeighborStateDB().keySet();
		Message shutdownMessage = MessageFactory
				.getShutdownClusterMessage(true);
		for (Node node : allNodes) {
			try {
				IoSession session = MessagingService.getInstance().send2Node(
						new InetSocketAddress(node.getIp(),
								ClusterContext.getHeartBeatPort()),
						shutdownMessage, new IoHandlerAdapter());
				session.close(false).awaitUninterruptibly();
			} catch (IOException e) {
				logger.error("", e);
			}
		}
	}

	@Override
	public void restart() {

	}

}
